﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using Xtee.CodeDom.Wrapper;
using Xtee.Core;
using Xtee.Core.Schema;

namespace Xtee.CodeDom.MetaInfo
{
    public class AttributeInfo:InfoBase
    {
        public XmlSchemaAttribute Attribute { get; set; }
        public XmlSchemaAttribute RefAttribute { get; set; }
        public override XmlQualifiedName QualifiedName => Attribute.QualifiedName;
        private XmlSchemaSimpleType XmlSchemaSimpleType
            => RefAttribute != null ? RefAttribute.AttributeSchemaType : Attribute.AttributeSchemaType;

        private XmlQualifiedName _schemaTypeName;
        public override XmlQualifiedName SchemaTypeName => _schemaTypeName ?? (_schemaTypeName = RefAttribute?.SchemaTypeName??Attribute.SchemaTypeName);

        private string _name;
        public override string Name
        {
            get
            {
                if (_name != null)
                    return _name;

                _name = Attribute.QualifiedName.Name.Pascalize();

                if (Owner != null && Owner.NameInfo.Name == Name) _name = _name + "0";

                return _name;
            }
        }

        private string _fullName;
        public sealed override string FullName
        {
            get
            {
                if (_fullName != null)

                    return _fullName;

                _fullName = new EntityClassNameInfo(SchemaTypeName, false, Resolver).GlobalName;

                if (SchemaTypeName.HasBuiltInType())
                    _fullName = TypeMappings.GetXsdType(SchemaTypeName.Name, SchemaTypeName.Namespace).FullName;

                return _fullName;
            }
        }

        private string _elementPath;
        public override string ElementPath => _elementPath??(_elementPath= XmlSchemaComplexTypeWrapper.GetElementPath(Attribute, null, null));

        private TypeInfo _typeInfo;
        public override TypeInfo TypeInfo => _typeInfo ?? (_typeInfo = new SimpleTypeInfo(FullName, XmlSchemaSimpleType, Owner));
        public override bool IsRequired => Attribute.Use == XmlSchemaUse.Required;
        public string DefaultValue => RefAttribute?.DefaultValue??Attribute.DefaultValue;
        public string FixedValue => RefAttribute?.FixedValue ?? Attribute.FixedValue;
        public override bool IsAnonymous => Attribute.IsAnonymous(Resolver);
        public override bool IsNullable => Attribute.Use != XmlSchemaUse.Required;
        public override bool IsArray => false;
        public AttributeInfo(XmlSchemaAttribute attribute, SchemaObjectClassInfo owner):base(owner)
        {
            Attribute = attribute;

            if (!Attribute.RefName.IsEmpty)
                RefAttribute = Attribute.RefName.ToSchemaAttribute(Resolver);
            
        }
        
    }
}
